import { ref, reactive, onMounted, onUnmounted } from 'vue'

export function useScreenScale(containerRef) {
  const scale = ref(1)
  const screenStyle = reactive({
    transform: 'scale(1)',
    transformOrigin: 'left top'
  })

  const calculateScale = () => {
    if (!containerRef.value) return

    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    const scaleX = windowWidth / 1920
    const scaleY = windowHeight / 1080
    const calculatedScale = Math.min(scaleX, scaleY)

    scale.value = calculatedScale
    screenStyle.transform = `scale(${calculatedScale})`
  }

  let resizeTimer = null
  const handleResize = () => {
    if (resizeTimer) clearTimeout(resizeTimer)
    resizeTimer = setTimeout(calculateScale, 100)
  }

  onMounted(() => {
    calculateScale()
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (resizeTimer) clearTimeout(resizeTimer)
  })

  return { scale, screenStyle }
}
